<template>
  <div ref="chartDom" :class="`w-full h-[${height ?? 400}px]`"></div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ChartKey } from "./type";
import echarts, { EChartsOption } from "./echarts";
import { debounce, merge } from "lodash-es";

const props = defineProps<{
  chartKey: ChartKey;
  height?: number;
}>();

let chart: Nullable<echarts.ECharts> = null;
let chartOptions: EChartsOption | undefined;
const chartDom = ref<HTMLDivElement | null>(null);
const register = inject(props.chartKey);
const { isDarkMode } = useTheme();

const handleOnChartResize = debounce(() => {
  if (chart) chart.resize();
}, 100);

const init = () => {
  chart && chart.dispose();
  chart = echarts.init(chartDom.value, isDarkMode.value ? "acm-dark" : "light");
  chartOptions && setOptions(chartOptions);
  window.removeEventListener("resize", handleOnChartResize);
  window.addEventListener("resize", handleOnChartResize);
};

const setLoading = (showLoading: boolean) => {
  if (showLoading) chart?.showLoading();
  else chart?.hideLoading();
};

const setOptions = (options: EChartsOption) => {
  chartOptions = merge(options, chartOptions);
  chart?.setOption(options);
};

watch(isDarkMode, init);

onMounted(async () => {
  await nextTick();
  init();
  register?.({
    setLoading,
    setOptions,
  });
});

onUnmounted(() => {
  window.removeEventListener("resize", handleOnChartResize);
  if (chart) chart.dispose();
});
</script>

<style scoped></style>
